//
//  WBRefreshControl.swift
//  SinaWeibo
//
//  Created by zhuangqianwei on 16/11/20.
//  Copyright © 2016年 zhuangqianwei. All rights reserved.
//

import UIKit

enum RefreshStatue: Int {
    case Normal = 0
    case Already
    case Refreshing
}

private let refreshHeight: CGFloat = 60
class WBRefreshControl: UIControl {
//KVO 观察对象的属性变化
    
    var statue: RefreshStatue = .Normal {
        didSet {
            switch statue {
            case .Normal:
                print("+++普通状态")
                tipLabel.text = "下拉刷新"
                indicator.stopAnimating()
                arrowIcon.isHidden = false
                //修改箭头的方向
                UIView.animate(withDuration: 0.25, animations: {
                    //修改形变
                    self.arrowIcon.transform = CGAffineTransform.identity
                })
                
                if oldValue == .Refreshing {
                    UIView.animate(withDuration: 0.25, animations: {
                        //修改形变
                        self.scrollView!.contentInset.top = self.scrollView!.contentInset.top - refreshHeight
                    })
                    
                }
                
            case .Already:
                print("+++准备状态")
                tipLabel.text = "松手刷新"
                //修改箭头的方向
                UIView.animate(withDuration: 0.25, animations: {
                    //修改形变
                    self.arrowIcon.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
            case .Refreshing:
                tipLabel.text = "正在刷新..."
                indicator.startAnimating()
                arrowIcon.isHidden = true
                //数据请求结束之后就应该恢复默认状态
                //如何触发事件
                sendActions(for: .valueChanged)
                //正在刷新状态有悬停的效果 修改contentInset.top
                UIView.animate(withDuration: 0.25, animations: {
                    //修改形变
                    self.scrollView!.contentInset.top = self.scrollView!.contentInset.top + refreshHeight
                })
                
            }
            //self.lastStatue = statue
        }
    }
    
    
    func endRefreshing() {
        
        //swift 中如何延迟执行
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            //将statue修改为normal状态
            self.statue = .Normal
        }
    }
    
    //设置一个固定大小
    override init(frame: CGRect) {
        
        let rect = CGRect(x: 0, y: -refreshHeight, width: ScreenWidth, height: refreshHeight)
        super.init(frame: rect)
        self.backgroundColor = randomColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //在什么时候设置KVO观察   -> 当刷新控件被添加到父视图上的时候开始设置KVO观察
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        if let fatherView = newSuperview as? UIScrollView {
            //设置观察
            self.scrollView = fatherView
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
            
        }
    }
    
    //观察的监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print("^^^^ \(change)")
        let offsetY = self.scrollView?.contentOffset.y ?? 0
        let targetOffetY = -(self.scrollView!.contentInset.top + refreshHeight)
        //offsety targetOffetY 进行比较判断状态 更新UI
        //正在被拽动
        if scrollView!.isDragging {
            if  statue == .Normal && offsetY < targetOffetY {
                //-125 < -124  准备刷新的状态
                statue = .Already
            } else if statue == .Already && offsetY > targetOffetY {
                //-110 > -124  默认状态
                statue = .Normal
            }
        } else {
            //用户停止拽动tableView && 当前状态是准备刷新状态  -> 正在刷新状态
            if statue == .Already {
                statue = .Refreshing
            }
        }
    }
    
    
    //设置UI界面
    private func setupUI() {
        addSubview(refreshbg)
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicator)
        
        //设置约束
        tipLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
        }
        arrowIcon.snp.makeConstraints { (make) in
            make.right.equalTo(tipLabel.snp.left).offset(-5)
            make.centerY.equalTo(tipLabel)
        }
        
        indicator.snp.makeConstraints { (make) in
            make.center.equalTo(arrowIcon)
        }
        refreshbg.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
        }
    }
    
    //懒加载
    var scrollView: UIScrollView?
    private lazy var tipLabel: UILabel = UILabel(title: "下拉起飞", textCololr: UIColor.orange, fontSize: 14)
    private lazy var arrowIcon: UIImageView = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    private lazy var indicator: UIActivityIndicatorView =  UIActivityIndicatorView(activityIndicatorStyle: .white)
    //自定义logo下拉图片
    private lazy var refreshbg: UIImageView = UIImageView(image: #imageLiteral(resourceName: "refreshbg"))
    
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
